package main

import (
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"synthesis-server/model"
	"time"
)

var jwtkey = []byte("sdu.edu.cn")
var str string
var TokenClaims Claims

type Claims struct {
	User model.User
	jwt.StandardClaims
}

func main() {
	user := model.User{1, "123456", "server"}
	expireTime := time.Now().Add(time.Hour * 4) //4个小时的有效期
	claims := &Claims{
		User: user,
		StandardClaims: jwt.StandardClaims{
			NotBefore: time.Now().Unix() - 60,
			ExpiresAt: expireTime.Unix(), //过期时间
			IssuedAt:  time.Now().Unix(), //颁发时间
			Issuer:    "127.0.0.1",       //签名颁发者
			Subject:   "user token",      //签名主题
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	_, err := token.SignedString(jwtkey) //形成加密串
	if err != nil {
		panic(err)
	}
	str = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJVc2VyIjp7IklEIjowLCJQd2QiOiIiLCJUeXBlIjoiIn0sImV4cCI6MTY1Njc2ODcyOSwiaWF0IjoxNjU2NzU0MzI5LCJpc3MiOiIxMjcuMC4wLjEiLCJuYmYiOjE2NTY3NTQyNjksInN1YiI6InVzZXIgdG9rZW4ifQ.FbEjQ2ihxi-5A7wNnREtdXHBIaseAKLUC1g-r4_bdBM"
	fmt.Println(str)
	TokenClaims = Claims{}
	jwt.ParseWithClaims(str, &TokenClaims, func(token *jwt.Token) (interface{}, error) {
		return jwtkey, nil
	})
	fmt.Println("解析是否正确：", TokenClaims.User)
}
